package com.example.shirospringboot.controller.clientController;

import com.example.shirospringboot.mapper.ClientMapper;
import com.example.shirospringboot.pojo.Client;
import com.example.shirospringboot.service.customService.CustomService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
//@RequestMapping("/custom")
public class customController {

    @Autowired
    ClientMapper clientMapper;

    @Autowired
    CustomService customService;

//    @RequestMapping("/customs")
//    public String customerInfo() throws JsonProcessingException {
//        Client client = clientMapper.queryClient();
//        ObjectMapper mapper = new ObjectMapper();
//        return mapper.writeValueAsString(client);
//    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "index";
    }

    @RequestMapping("/login")
    public String customLogin(HttpSession session,String username, String password, Model model){
        //获取当前用户
        Subject subject= SecurityUtils.getSubject();
        //封装用户登录数据
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);


        try {
            subject.login(usernamePasswordToken);

            Client client = customService.queryClient(username);
            session.setAttribute("loginUser",username);
            session.setAttribute("clientId",client.getCustomId());
            System.out.println(client.getCustomId());
            return "dashboard";
        } catch (UnknownAccountException e) {//用户名不存在
            model.addAttribute("msg","账号错误");
            return "index";
        }
        catch (IncorrectCredentialsException e) {//密码错误
            model.addAttribute("msg","密码错误");
            return "index";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session, Model model) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        model.addAttribute("msg","安全退出！");
        return "index";
    }

}
